package com.qf.shiro2204.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 用于获取 IOC容器对象的 工具类
 */
@Component
public class ApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext ctx;

    /**
     * SPring ioc容器在创建这个 类的对象时，会回调如下方法，并且把IOC容器对象自身作为参数传递进来
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ctx = applicationContext;
    }

    // 根据beanname获取 bean对象
    public static Object getBean(String beanname){
        return ctx.getBean(beanname);
    }

    // 根据 class对象获取 bean对象
    public static <T> T getBean(Class<T> clazz){
        return ctx.getBean(clazz);
    }
}
